/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * TelaPesquisaAgenda.java
 *
 * Created on 31/03/2012, 10:38:21
 */

package agenda.tela;

import agenda.bean.Contato;
import agenda.bean.Tabela;
import agenda.controle.ControleAgenda;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Antonio
 */
public class TelaPesquisaAgenda extends javax.swing.JFrame {
    private ControleAgenda controle;
    private Tabela dadosTabela;
    private DefaultTableModel model;

    /** Creates new form TelaPesquisaAgenda */
    public TelaPesquisaAgenda() {
        controle = new ControleAgenda();
        dadosTabela = controle.pesquisar("\"Nome\"", "%");
        model = new DefaultTableModel(dadosTabela.getLinhas(),
                                      dadosTabela.getColunas());
        initComponents();
    }

    private void atualizaLista() {
        String coluna = tPesquisandoPor.getSelectedItem().toString();
        String parametro = tPesquisa.getText();
        parametro = "%" + parametro + "%";
        coluna = "\"" + coluna + "\"";
        dadosTabela = controle.pesquisar(coluna, parametro);
        model.setDataVector(dadosTabela.getLinhas(), dadosTabela.getColunas());
        tabela.updateUI();
    }

    public Integer getIdSelecionado() {
        int row = tabela.getSelectedRow();
        if (row == -1) {
            return -1;
        }
        try {
            Integer id = Integer.parseInt(tabela.getValueAt(row, 0).toString());
            return id;
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        tPesquisandoPor = new javax.swing.JComboBox(dadosTabela.getColunas());
        jLabel3 = new javax.swing.JLabel();
        tPesquisa = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        tabela = new javax.swing.JTable();
        bNovo = new javax.swing.JButton();
        bAlterar = new javax.swing.JButton();
        bExcluir = new javax.swing.JButton();
        bFechar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 24));
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("Agenda de Contatos");

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 18));
        jLabel2.setText("Pesquisando por: ");

        tPesquisandoPor.setFont(new java.awt.Font("Tahoma", 1, 18));
        tPesquisandoPor.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                tPesquisandoPorItemStateChanged(evt);
            }
        });

        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 18));
        jLabel3.setText("Digite o Texto a ser Pesquisado:");

        tPesquisa.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        tPesquisa.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                tPesquisaKeyReleased(evt);
            }
        });

        jScrollPane1.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
        jScrollPane1.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);

        tabela.setModel(model);
        jScrollPane1.setViewportView(tabela);

        bNovo.setFont(new java.awt.Font("Tahoma", 1, 16));
        bNovo.setText("Novo");
        bNovo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bNovoActionPerformed(evt);
            }
        });

        bAlterar.setFont(new java.awt.Font("Tahoma", 1, 16));
        bAlterar.setText("Alterar");
        bAlterar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bAlterarActionPerformed(evt);
            }
        });

        bExcluir.setFont(new java.awt.Font("Tahoma", 1, 16));
        bExcluir.setText("Excluir Contato");
        bExcluir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bExcluirActionPerformed(evt);
            }
        });

        bFechar.setFont(new java.awt.Font("Tahoma", 1, 16));
        bFechar.setText("Fechar");
        bFechar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bFecharActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(67, 67, 67)
                        .addComponent(bNovo, javax.swing.GroupLayout.PREFERRED_SIZE, 121, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(bAlterar, javax.swing.GroupLayout.PREFERRED_SIZE, 119, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 166, Short.MAX_VALUE)
                        .addComponent(bExcluir)
                        .addGap(143, 143, 143)
                        .addComponent(bFechar))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 860, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(175, 175, 175)
                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 565, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(tPesquisandoPor, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, 164, Short.MAX_VALUE))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(tPesquisa, javax.swing.GroupLayout.DEFAULT_SIZE, 670, Short.MAX_VALUE)
                            .addComponent(jLabel3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 670, Short.MAX_VALUE))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(17, 17, 17)
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(11, 11, 11)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addGap(1, 1, 1)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(tPesquisa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(tPesquisandoPor, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 319, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(bFechar)
                    .addComponent(bNovo)
                    .addComponent(bExcluir)
                    .addComponent(bAlterar))
                .addContainerGap(13, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void bFecharActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bFecharActionPerformed
        System.exit(0);
    }//GEN-LAST:event_bFecharActionPerformed

    private void tPesquisaKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tPesquisaKeyReleased
        atualizaLista();
    }//GEN-LAST:event_tPesquisaKeyReleased

    private void tPesquisandoPorItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_tPesquisandoPorItemStateChanged
        atualizaLista();
    }//GEN-LAST:event_tPesquisandoPorItemStateChanged

    private void bExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bExcluirActionPerformed
        Integer id = getIdSelecionado();
        if (id > 0) {
            if (JOptionPane.showConfirmDialog(null, "Confirma a Exclusão do Contato Selecionado e seus Telefones?",  "Confirma Exclusão", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
                // confirmou.
                if (controle.excluir(id)) {
                    JOptionPane.showMessageDialog(null, "Contato Excluido com Sucesso!");
                } else {
                    JOptionPane.showMessageDialog(null, "Erro ao Excluir. Tente Novamente.");
                }
                atualizaLista();
            }
        } else {
            JOptionPane.showMessageDialog(null, "Nenhum Contato Selecionado para Excluir!");
        }
    }//GEN-LAST:event_bExcluirActionPerformed

    private void bNovoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bNovoActionPerformed
        TelaCadastroAgenda tca = new TelaCadastroAgenda(null, true);
        tca.setVisible(true);
        atualizaLista();
    }//GEN-LAST:event_bNovoActionPerformed

    private void bAlterarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bAlterarActionPerformed
        Integer id = getIdSelecionado();
        if (id > 0) {
            Contato c = controle.carregaContato(id);
            TelaCadastroAgenda tca = new TelaCadastroAgenda(null, true);
            tca.mostra(c);
            tca.setVisible(true);
            atualizaLista();
        } else {
            JOptionPane.showMessageDialog(null, "Nenhum Contato Selecionado para Alterar!");
        }
    }//GEN-LAST:event_bAlterarActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new TelaPesquisaAgenda().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton bAlterar;
    private javax.swing.JButton bExcluir;
    private javax.swing.JButton bFechar;
    private javax.swing.JButton bNovo;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField tPesquisa;
    private javax.swing.JComboBox tPesquisandoPor;
    private javax.swing.JTable tabela;
    // End of variables declaration//GEN-END:variables

}
